#include <iostream>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <cstring>
#include <signal.h>
using namespace std;

long long count = 0;

void Usage(char* str)
{
    cout << "Usage:\n";
    cout << "\t" << str << " signal 信号 进程pid" << endl;
    cout << "\t" << str << " raise 信号 " << endl;
    cout << "\t" << str << " abort" << endl;
    cout << "\t" << str << " alarm 秒数 " << endl;
}
void myhandler(int sig)
{
    // cout << count << endl;  // 6亿左右
    cout << "signal: " << sig << endl;
    exit(0);
}
void signal(char* argv[])
{   
    int sig = atoi(argv[2]);
    int pid = atoi(argv[3]);
    int n = kill(pid, sig);
    if(n == -1)
    {
        cout << errno << ":" << strerror(errno) << endl;
        exit(errno);
    }
}
void raise(char* argv[])
{
    signal(atoi(argv[2]), myhandler);
    int sig = atoi(argv[1]);
    if(!raise(sig))
    {
        cout << errno << ":" << strerror(errno) << endl;
        exit(errno);
    }
}
void abort(int condition)
{
    signal(SIGABRT, myhandler);
    abort();
}
void alarm(char* argv[])
{
    signal(SIGALRM, myhandler);
    int times = atoi(argv[2]);
    alarm(times);
    while(true) count++;  // 6亿多
    // {
    //     // cout << count++ << endl; // 20多万
    //     // printf("%d\r",count++); // 40多万
    // }
}

int main(int argc, char* argv[])
{
    if(argc > 4 || argc < 2)
    {
        Usage(argv[0]);
        return 0;
    }
    // ./mysignal abort
    else if(argc == 2)
    {
        if(strcmp(argv[1], "abort") == 0)
        abort(1);
        else
        cout << "参数不对" << endl;
    }
    // ./mysignal raise 9
    else if(argc == 3)
    {
        if(strcmp(argv[1], "raise") == 0)
        raise(argv);
        else if(strcmp(argv[1], "alarm") == 0)
        alarm(argv);
        else
        cout << "参数不对" << endl;
    }
    // ./mysignal signal 9 pid
    else if(argc == 4)
    {
        if(strcmp(argv[1], "signal") == 0)
        signal(argv);
        else
        cout << "参数不对" << endl;
    }

    return 0;
}